package com.bw.demo_touch.neibu;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/27 10:22
 * @Description :
 */
public class ChildScrollView extends ScrollView {
    public ChildScrollView(Context context) {
        super(context);
    }

    public ChildScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ChildScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ChildScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("ChildScrollView", "dispatchTouchEvent: ");
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 内部拦截法
     * @param ev The motion event being dispatched down the hierarchy.
     * @return
     */
    private float mLastX;
    private float mLastY;
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        float x = ev.getX();
        float y = ev.getY();
        int action = ev.getAction();//事件类型

        if (action == MotionEvent.ACTION_DOWN){
            mLastX = x;
            mLastY = y;
            getParent().requestDisallowInterceptTouchEvent(true);//ture告诉父控件不要拦截，false告诉父控件可以拦截
        }else if (action == MotionEvent.ACTION_MOVE){
            float dx = Math.abs(x - mLastX);
            float dy = Math.abs(y - mLastY);
            if (dx < dy){//纵向滑动
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        }
        return super.onInterceptTouchEvent(ev);
    }
}
